package com.salt.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.salt.common.Result;
import com.salt.entity.IdleAffiliateCpaIncomeDetail;
import com.salt.entity.User;
import com.salt.service.IdleAffiliateCpaIncomeDetailService;
import com.salt.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 闲鱼联盟CPA佣金明细控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/cpa-income")
@RequiredArgsConstructor
public class IdleAffiliateCpaIncomeDetailController {

    private final IdleAffiliateCpaIncomeDetailService incomeDetailService;

    /**
     * 获取佣金明细汇总数据
     * @param startDate 开始日期，格式：yyyy-MM-dd
     * @param endDate 结束日期，格式：yyyy-MM-dd
     * @return 汇总数据
     */
    @GetMapping("/summary")
    public Result<Map<String, Object>> getIncomeSummary(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        
        log.info("接收到CPA佣金明细汇总查询请求，开始日期：{}，结束日期：{}", startDate, endDate);

        try {
            // 获取当前用户
            User user = UserContext.getUser();
            if (user == null) {
                return Result.error("用户未登录");
            }

            // 转换日期字符串为LocalDate
            LocalDate start = LocalDate.parse(startDate);
            LocalDate end = LocalDate.parse(endDate);
            
            // 转换为Date类型，并设置时间范围
            Date startDateTime = java.util.Date.from(
                start.atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toInstant()
            );
            Date endDateTime = java.util.Date.from(
                end.atTime(LocalTime.MAX).atZone(java.time.ZoneId.systemDefault()).toInstant()
            );
            
            Map<String, Object> summary = incomeDetailService.getIncomeSummary(startDateTime, endDateTime, user.getInviteCode());
            return Result.success(summary);
        } catch (Exception e) {
            log.error("查询CPA佣金明细汇总数据失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询佣金明细数据
     * @param current 当前页码，从1开始
     * @param size 每页大小
     * @param startDate 开始日期，格式：yyyy-MM-dd
     * @param endDate 结束日期，格式：yyyy-MM-dd
     * @param state 账单状态：1-待发放，2-已发放，3-已取消
     * @param keyword 关键词（账单ID或备注）
     * @return 分页数据
     */
    @GetMapping("/page")
    public Result<IPage<IdleAffiliateCpaIncomeDetail>> pageQuery(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) Integer state,
            @RequestParam(required = false) String keyword) {
        try {
            // 获取当前用户
            User user = UserContext.getUser();
            if (user == null) {
                return Result.error("用户未登录");
            }

            // 创建分页对象
            Page<IdleAffiliateCpaIncomeDetail> page = new Page<>(current, size);

            // 转换日期字符串为Date类型
            Date startDateTime = null;
            Date endDateTime = null;
            
            if (startDate != null && !startDate.isEmpty()) {
                LocalDate start = LocalDate.parse(startDate);
                startDateTime = java.util.Date.from(
                    start.atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toInstant()
                );
            }
            
            if (endDate != null && !endDate.isEmpty()) {
                LocalDate end = LocalDate.parse(endDate);
                endDateTime = java.util.Date.from(
                    end.atTime(LocalTime.MAX).atZone(java.time.ZoneId.systemDefault()).toInstant()
                );
            }

            // 执行分页查询
            IPage<IdleAffiliateCpaIncomeDetail> pageResult = incomeDetailService.pageQuery(
                    page,
                    startDateTime,
                    endDateTime,
                    state,
                    keyword,
                    user.getInviteCode()
            );

            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询CPA佣金明细失败", e);
            return Result.error(e.getMessage());
        }
    }
} 